<template>
    <el-main>
        <el-form :model="searchModel" ref="searchForm" label-width="80px" :inline="true" size="small">
            <el-form-item>
                <el-input v-model="searchModel.roleName" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="search(pageNo, pageSize)">查询</el-button>
                <el-button icon="el-icon-refresh-right" @click="resetValue()">重置</el-button>
                <el-button type="success" icon="el-icon-plus" @click="openAddWindow()" v-if="$hasPermission('sys:role:add')">新增</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="roleList" :height="tableHeight" border stripe style="width: 100%; margin-bottom: 10px;">
            <el-table-column prop="roleCode" label="角色编码" width="160" align="center"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="remark" label="角色备注"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button icon="el-icon-edit" type="primary" size="small" @click="handleEdit(scope.row)" v-if="$hasPermission('sys:role:edit')">编辑</el-button>
                    <el-button icon="el-icon-delete" type="danger" size="small"
                        @click="handleDelete(scope.row)" v-if="$hasPermission('sys:role:delete')">删除</el-button>
                    <el-button icon="el-icon-setting" type="primary" size="small"
                        @click="assignRole(scope.row)" v-if="$hasPermission('sys:role:assign')">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页工具栏 -->
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pageNo" :page-sizes="[10, 20, 30, 40, 50]" :page-size="10"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <system-dialog :title="roleDialog.title" :width="roleDialog.width" :height="roleDialog.height"
            :visible="roleDialog.visible" @onClose="onClose()" @onConfirm="onConfirm()">
            <div slot="content">
                <el-form :model="role" ref="roleForm" :rules="rules" label-width="80px" :inline="false" size="small">
                    <el-form-item label="角色编码" prop="roleCode">
                        <el-input v-model="role.roleCode"></el-input>
                    </el-form-item>
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="role.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述">
                        <el-input type="textarea" v-model="role.remark" :rows="5"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </system-dialog>

        <system-dialog :title="assignDialog.title" :width="assignDialog.width" :height="assignDialog.height"
            :visible="assignDialog.visible" @onClose="onAssignClose()" @onConfirm="onAssignConfirm()">
            <div slot="content">
                <el-tree ref="assignTree" :data="assignTreeData" node-key="id" :props="defaultProps" empty-text="暂无数据"
                    :show-checkbox="true" :highlight-current="true" default-expand-all>
                </el-tree>
            </div>
        </system-dialog>
    </el-main>
</template>

<script>
import SystemDialog from '@/components/system/SystemDialog.vue'
import { getRoles, addRole, updateRole, deleteRole, checkRole, getAssignTree, assignSave } from '@/api/role';
import leafUtils from '@/utils/leaf'

export default {
    name: "roleList",
    components: {
        SystemDialog
    },
    data() {
        return {
            searchModel: {
                roleName: "",
                pageNo: 1,
                pageSize: 10,
                userId: this.$store.getters.userId
            },
            pageNo: 1,
            pageSize: 10,
            total: 0,
            roleList: [],
            tableHeight: 0,
            roleDialog: {
                type: "add",
                title: "",
                width: 230,
                height: 500,
                visible: false
            },
            rules: {
                roleCode: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
                roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
            },
            assignDialog: {
                title: "分配权限",
                width: 450,
                height: 300,
                visible: false
            },
            defaultProps: {
                children: "children",
                label: "label"
            },
            role: {
                id: "",
                roleCode: "",
                roleName: "",
                remark: "",
                createUser: this.$store.getters.userId
            },
            assignTreeData: [],
            roleId: ""
        }
    },
    created() {
        this.search()
    },
    mounted() {
        this.$nextTick(() => {
            this.tableHeight = window.innerHeight - 220
        })
    },
    methods: {
        async search(pageNo = 1, pageSize = 10) {
            this.searchModel.pageNo = pageNo
            this.searchModel.pageSize = pageSize
            let res = await getRoles(this.searchModel)
            if (res.success) {
                this.roleList = res.data.records
                this.total = res.data.total
            }
        },
        resetValue() {
            this.searchModel.roleName = ''
            this.search(this.pageNo, this.pageSize)
        },
        openAddWindow() {
            this.$resetForm('roleForm', this.role)
            this.roleDialog.title = "新增角色"
            this.roleDialog.visible = true
            this.roleDialog.type = "add"
        },
        onClose() {
            this.roleDialog.visible = false
        },
        onConfirm() {
            if (this.roleDialog.type === "add") {
                this.$refs.roleForm.validate(async (valid) => {
                    if (valid) {
                        let res = await addRole(this.role)
                        if (res.success) {
                            this.$message.success(res.message)
                            this.search(this.pageNo, this.pageSize)
                            window.location.reload()
                            this.roleDialog.visible = false
                        } else {
                            this.$message.error(res.message)
                        }
                    }
                })

            } else if (this.roleDialog.type === "edit") {
                this.$refs.roleForm.validate(async (valid) => {
                    if (valid) {
                        let res = await updateRole(this.role)
                        if (res.success) {
                            this.$message.success(res.message)
                            this.search(this.pageNo, this.pageSize)
                            window.location.reload()
                            this.roleDialog.visible = false
                        } else {
                            this.$message.error(res.message)
                        }
                    }
                })
            }
        },
        handleEdit(row) {
            this.$objCopy(row, this.role)
            this.roleDialog.title = "修改角色"
            this.roleDialog.visible = true
            this.roleDialog.type = "edit"
        },
        async handleDelete(row) {
            let check = await checkRole({ id: row.id })
            if (!check.success) {
                this.$message.warning(check.message)
            } else {
                let confirm = await this.$myconfirm("确认要删除该数据吗?")
                if (confirm) {
                    let res = await deleteRole({ id: row.id })
                    if (res.success) {
                        this.$message.success(res.message)
                        this.search(this.pageNo, this.pageSize)
                        window.location.reload()
                    } else {
                        this.$message.error(res.message)
                    }
                }
            }
        },
        async assignRole(row) {
            this.roleId = row.id
            let params = {
                roleId: row.id,
                userId: this.$store.getters.userId
            }
            let res = await getAssignTree(params)
            if (res.success) {
                let { permissionList } = res.data
                let { checkList } = res.data
                let setLeaf = leafUtils()
                let newPermissionList = setLeaf(permissionList)
                this.assignTreeData = newPermissionList
                this.$nextTick(() => {
                    let nodes = this.$refs.assignTree.children
                    this.setChild(nodes, checkList)
                })

                this.assignDialog.visible = true
                this.assignDialog.title = `给[${row.roleName}]分配权限`
            }
        },
        setChild(childNodes, checkList) {
            if (childNodes && childNodes.length > 0) {
                for (let i = 0; i < childNodes.length; i++) {
                    let node = this.$refs.assignTree.getNode(childNodes[i])                    
                    if (checkList && checkList.length > 0) {
                        for (let j = 0; j < checkList.length; j++) {                            
                            if (checkList[j] === childNodes[i].id) {                                                                              
                                if (childNodes[i].open) {
                                    this.$refs.assignTree.setChecked(node, true)
                                    break
                                }
                            }
                        }
                    }

                    if (childNodes[i].children) {
                        this.setChild(childNodes[i].children, checkList)
                    }
                }
            }
        },
        onAssignClose() {
            this.assignDialog.visible = false
        },
        async onAssignConfirm() {
            let ids = this.$refs.assignTree.getCheckedKeys()
            let pids = this.$refs.assignTree.getHalfCheckedKeys()
            let listId = ids.concat(pids)
            let parms = {
                roleId: this.roleId,
                list: listId
            }
            let res = await assignSave(parms)
            if (res.success) {
                this.assignDialog.visible = false
                this.$message.success(res.message)
            } else {
                this.$message.error(res.message)
            }
        },
        handleSizeChange(size) {
            this.pageSize = size
            this.search(this.pageNo, size)
        },
        handleCurrentChange(page) {
            this.pageNo = page
            this.search(page, this.pageSize)
        }
    }
}
</script>

<style lang="scss" scoped></style>